package com.macro.mall.portal.util;

import java.util.*;

/**
 * 随机获取
 */
public class SplitArrayUtils {

    /**
     * 随机获取长度为size的list<br>
     * 获取的list顺序也是随机的
     * 截取size比list长或相等,则返回全部
     *
     * @param source
     * @param size
     * @return
     */
    public static <T> List<T> getRandomList(List<T> source, int size) {
        if (source.size() <= size) {
            Collections.shuffle(source);
            return source;
        }
        List<T> target = new ArrayList<>(size);
        Set<Integer> set = new HashSet<>(size);
        while (set.size() < size) {
            int random = new Random().nextInt(source.size());
            if (!set.contains(random)) {
                set.add(random);
                target.add(source.get(random));
            }
        }
        return target;

    }
}
